package com.example.s09thymeleaf.controller;

import com.example.s09thymeleaf.entity.Teacher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ValidatorController {
    @GetMapping("/validator")
    public String validatorPage(Model model){
        Teacher teacher=new Teacher();
        teacher.setName("张三");
        teacher.setAge(40);
        teacher.setEmail("1212@qq.com");
        teacher.setPassword("123456ab");
        String strDate="1984-01-01";
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        Date birthday =null;
        try {
            birthday = format.parse(strDate);
        }catch (Exception e){
            birthday =new Date();
        }
        teacher.setBirthday(birthday);
        model.addAttribute("teacher",teacher);
        return "validator";
    }
//    @PostMapping("/toValidator")
//    public String toValidator(@Validated Teacher teacher, BindingResult bindingResult ,Model model){
//        if(bindingResult.hasErrors())
//            return "validator";//当表单中输入的内容不符合要求时，跳转到validator.html页面
//        else {
//            model.addAttribute("teacher",teacher);
//            return "success";
//        }
//    }
    //下面的代码跟上面注释的代码的功能一样
    @PostMapping("/toValidator")
    public String toValidator(@ModelAttribute("teacher") @Validated Teacher teacher, BindingResult bindingResult ){
        if(bindingResult.hasErrors())
            return "validator";//当表单中输入的内容不符合要求时，跳转到validator.html页面
        else {

            return "success";
        }
    }
}
